package cn.ibizlab.odoo.activiti.service.impl;

import cn.ibizlab.odoo.activiti.entity.TaskInfo;
import cn.ibizlab.odoo.activiti.service.IWFCoreService;
import cn.ibizlab.odoo.activiti.util.TaskUtil;
import com.alibaba.fastjson.JSONObject;
import org.activiti.api.process.runtime.ProcessRuntime;
import org.activiti.api.task.runtime.TaskRuntime;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.DelegationState;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.List;
import java.util.Map;


@Service
public class WFCoreService implements IWFCoreService {

    @Autowired
    ProcessRuntime  processRuntime;

    @Autowired
    TaskRuntime taskRuntime;

    @Autowired
    RepositoryService repositoryService;

    @Autowired
    RuntimeService runtimeService;

    @Autowired
    TaskService taskService;

    @Autowired
    HistoryService historyService;

    @Autowired
    TaskUtil taskUtil;

    @Override
    public String wfStart(JSONObject et) {

        String processId=et.getString("processid");

        Map<String, Object> variables=et.getJSONObject("variables");

        if (StringUtils.isEmpty(processId)) {
            return "processId error";
        }

        ProcessInstance instance = runtimeService.startProcessInstanceByKey(processId, variables);
        System.out.println("流程实例ID:" + instance.getId());
        System.out.println("流程定义ID:" + instance.getProcessDefinitionId());
        System.out.println("*****************************************************************************");

        return "success";
    }

    @Override
    public String wfSubmit(JSONObject et) {

        String taskId=et.getString("taskid");

        Map<String, Object> variables=et.getJSONObject("variables");

        if (StringUtils.isEmpty(taskId)) {
            return "taskId error";
        }

        taskService.setVariables(taskId, variables);

        // 若是委托任务，请先解决委托任务
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        if (DelegationState.PENDING.equals(task.getDelegationState())) {
            return "resolve delegation first";
        }

        taskService.complete(taskId);
        System.out.println("任务完成");
        System.out.println("任务ID:" + taskId);
        System.out.println("任务处理结果:" + variables);
        System.out.println("*****************************************************************************");

        return "success";
    }

    @Override
    public void wfClose(JSONObject et) {

    }

    @Override
    public void wfGoto(JSONObject et) {

    }

    @Override
    public void wfRestart(JSONObject et) {

    }

    @Override
    public void wfRollback(JSONObject et) {

    }

    @Override
    public void wfSendBack(JSONObject et) {

    }

    @Override
    public void wfReassign(JSONObject et) {

    }

    @Override
    public void wfMarkRead(JSONObject et) {

    }

    @Override
    public String wfDeploy(JSONObject et) {

        String deployFilePath =et.getString("deployfilepath");

        if(StringUtils.isEmpty(deployFilePath))
            return "部署文件名称不能为空!";

        // 创建一个部署对象
        Deployment deploy = repositoryService.createDeployment()
                .addClasspathResource("processes/" + deployFilePath).deploy();

        String deployId=deploy.getId();
        System.out.println("部署成功:" + deploy.getId());
        System.out.println("*****************************************************************************");
        return deployId;
    }

    @Override
    public TaskInfo getWFCurStep(JSONObject et) {

      String processInstanceId = et.getString("instanceid");

        Task task;
        TaskInfo taskInfo =null;
        if (StringUtils.isEmpty(processInstanceId)) {
            return taskInfo;
        }

            task = taskService.createTaskQuery()// 创建查询对象
                    .processInstanceId(processInstanceId)// 通过流程实例id来查询当前任务
                    .singleResult();// 获取单个查询结果

            if (task == null) {
                System.out.println("流程已结束");
                System.out.println("流程实例ID:" + processInstanceId);
                System.out.println("*****************************************************************************");
                return taskInfo;
            }

            taskInfo=taskUtil.covert2Task(task);

            System.out.println("任务ID:" + taskInfo.getId());
            System.out.println("任务名称:" + taskInfo.getName());
            System.out.println("任务的创建时间:" + taskInfo.getCreateTime());
            System.out.println("任务的办理人:" + taskInfo.getAssignee());
            System.out.println("流程实例ID：" + taskInfo.getProcessInstanceId());
            System.out.println("执行对象ID:" + taskInfo.getExecutionId());
            System.out.println("流程定义ID:" + taskInfo.getProcessDefinitionId());
            System.out.println("*****************************************************************************");

        return taskInfo;
    }

    @Override
    public List<HistoricActivityInstance> getWFHisStep(JSONObject et) {

        String instanceId = et.getString("instanceid");

        if(StringUtils.isEmpty(instanceId))
            return null;

        List<HistoricActivityInstance> historicTasks = null;
        try {
            historicTasks= historyService.createHistoricActivityInstanceQuery()
                    .processInstanceId(instanceId).list();
            if (historicTasks != null && historicTasks.size() > 0) {
                for (HistoricActivityInstance hai : historicTasks) {
                    System.out.println(hai.getId());
                    System.out.println("步骤ID：" + hai.getActivityId());
                    System.out.println("步骤名称：" + hai.getActivityName());
                    System.out.println("执行人：" + hai.getAssignee());
                    System.out.println("*****************************************************************************");
                }
            }
        } catch (Exception e) {
            return historicTasks;
        }
        return historicTasks;
    }

}
